import json

from django.http import JsonResponse
from django.views import View
from rest_framework import status
from rest_framework.generics import GenericAPIView, ListAPIView, get_object_or_404
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.settings import api_settings
from djangoDrf.serializers import MyRefreshToken, GroupSerializer
from task.models import Group, GroupUser

from user.models import User
from django.contrib.auth.hashers import check_password

from user.serializers import UserSerializer


class UserView(GenericAPIView):

    queryset = User.objects.filter(is_delete=False)

    serializer_class = api_settings.TOKEN_OBTAIN_SERIALIZER

    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):

        username = request.data.get('username')
        password = request.data.get('password')

        queryset = self.get_queryset().filter(username=username)

        if not queryset:
            return Response({'detail': '用户名不正确'}, status=status.HTTP_401_UNAUTHORIZED)

        # 获取对应密码
        user = queryset[0]

        # 比较密码
        if not check_password(password, user.password):
            return Response({'detail': '密码不正确'}, status=status.HTTP_401_UNAUTHORIZED)

        # 判断当前账户是否激活
        if not user.is_active:
            return Response({'detail': '用户或密码不正确'}, status=status.HTTP_401_UNAUTHORIZED)

        # 返回令牌
        refresh = MyRefreshToken.for_user(user)

        data = {
            'refresh': str(refresh),
            'access': str(refresh.access_token),
        }

        return Response(data, status=status.HTTP_200_OK)


# 添加组
class GroupCreateView(APIView):
    def post(self, request):
        serializer = GroupSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# 分页
class GroupPagination(PageNumberPagination):
    page_size = 10  # 每页显示10个项
    page_size_query_param = 'page_size'  # 客户端可以传递 page_size 来修改每页数量
    max_page_size = 100

    # 可以重写分页响应的格式
    def get_paginated_response(self, data):
        print(f"分页返回数据: {data}")  # 打印分页数据，确保分页操作生效
        return Response({
            'count': self.page.paginator.count,
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'results': data
        })


class GroupListView(ListAPIView):
    queryset = Group.objects.all().order_by('id')  # 明确排序
    serializer_class = GroupSerializer
    permission_classes = [AllowAny]
    pagination_class = GroupPagination  # 这里添加分页类

    def get(self, request, *args, **kwargs):
        print("请求的分页参数：", request.query_params)  # 打印请求参数
        response = super().get(request, *args, **kwargs)
        print("分页数据：", response.data)  # 打印分页结果
        return response



class UserListAPIView(APIView):
    def get(self, request):
        users = User.objects.filter(is_staff=False) # 只查普通用户
        return Response(UserSerializer(users, many=True).data)


class GroupUserAPIView(APIView):
    def get(self, request, pk):
        group = Group.objects.get(pk=pk)
        users = group.users.all()  # 假设 ManyToManyField 到 User
        return Response([user.id for user in users])

    def post(self, request, pk):
        group = Group.objects.get(pk=pk)
        user_ids = request.data.get('user_ids', [])
        group.users.set(user_ids)
        return Response({"status": "success"}, status=status.HTTP_200_OK)


# 修改组名
class GroupDetailView(APIView):
    def get(self, request, pk):
        group = get_object_or_404(Group, pk=pk)
        serializer = GroupSerializer(group)
        return Response(serializer.data)

    def put(self, request, pk):
        group = get_object_or_404(Group, pk=pk)
        serializer = GroupSerializer(group, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        group = get_object_or_404(Group, pk=pk)
        group.delete()
        return Response({"status": "deleted"}, status=status.HTTP_204_NO_CONTENT)


